<template>
	<div class="attendee">
		<!--<div v-if="waiting" class="waiting_content">-->
		<!--当前会议“{{meeting_title}}”-->
		<!--</div>-->
		<div v-if="waiting" class="waiting_content">
			<p style="padding-bottom: 30px">“{{meeting_title}}”</p>
			<p>会议即将开始...</p>
		</div>
		<div v-if="!waiting">
			<div class="title">
				<div class="meeting-theme">{{meeting_title}}</div>
				<div class="section">环节:{{link_info.title}}</div>
			</div>
			<div class="ppt">
				<image v-if="content.type == 'content'" class="ppt-img" mode="aspectFit" :src='content.img_url'></image>
				<video v-if="content.type == 'video'" class="ppt-img" mode="aspectFit" :src='content.video_url' autoplay></video>
			</div>
			<div class="ppt-text">{{content.content}}</div>
			<div class="talk">
				<span style="padding: 5rpx;color: white">讨论内容展示：</span>
				<scroll-view class="talk-warp" :scroll-top="scrollTop" scroll-y="true">
					<ul class="talk-box">
						<li class="talk-list" v-for="(item,index) in talkList" :key="index">
							<div class="talk-list-info">
								<img :src="item.photo_url">
								<span style="color:#fff;">{{item.nickname}}</span>
							</div>
							<span style="color:#fff;font-size:12px;">:</span>
							<div class="talk-list-content" v-if="item.type=='text'">{{item.chat_content}}</div>
							<div class="talk-list-content" v-else style="position: relative" @click="playAudio(index)">
								<img v-if="is_display[index] == 0" :data-id="is_display[index]" style="height: 50px;width: 45px" src="http://file.rzkeji.com/web/dang/wxapp/icon_audio.png">
								<img v-if="is_display[index] == 1" :data-id="is_display[index]" class="icon-audio" style="height: 50px;width: 45px" src="http://file.rzkeji.com/web/dang/wxapp/icon_audio.png">
							</div>
						</li>
					</ul>
				</scroll-view>
				<div class="talk-input">
					<!-- <img src="../../static/img/voice.png"></img> -->
					<input type="text" maxlength="-1" v-model="talk" placeholder="请输入讨论内容" placeholder-style="color:#fff">
					<img style="margin-right: 10rpx;width: 80rpx;height: 75rpx" src="http://file.rzkeji.com/web/dang/wxapp/yy.png" @longpress="getAudio" @touchend="stopAudio">
					<span @click="UserSendMessage('text')">发送</span>
				</div>
				<div>
					<button style="margin: 30rpx 0" @click="startSpeak">广播发言</button>
				</div>
			</div>
			<div class="attendee-count">
				<div class="attendee-count-title">现场参会人员({{joinList.here.length}}人):</div>
				<div class="attendee-count-content">
					<div class="attendee-count-list" v-for="(item,index) in joinList.here" :key="index">
						<img :src="item.photo_url"></img>
						<span>{{item.nickname}}</span>
					</div>
				</div>
			</div>
			<div class="attendee-count">
				<div class="attendee-count-title">远程参会人员({{joinList.remote.length}}人):</div>
				<div class="attendee-count-content">
					<div class="attendee-count-list" v-for="(item,index) in joinList.remote" :key="index">
						<img :src="item.photo_url"></img>
						<span>{{item.nickname}}</span>
					</div>
				</div>
			</div>
			<div class="waiting_out">
				<div class="send" @click="outWaiting">退出会议</div>
			</div>
		</div>
		<div class="qrcodenav" @click="openQRcode">
			<img src="../../static/img/QRcode.png">
		</div>
		<div class="maxqrcode" @click="openQRcode" v-if="bigcode">
			<img :src="qr_info.qr_attendee" mode="widthFix">
		</div>

		<!-- 发言弹窗 -->
		<div class="speak" v-if="is_speaking">
			<div class="bk"></div>
			<div class="content">
				<p>您正在发言，每60秒发送一段，点击"关闭发言"停止发言！</p>
				<p>{{speaking_status}}(<span>{{speaking_time}}</span>秒)</p>
				<button @click="closeSpeaking">关闭发言</button>
			</div>
		</div>
	</div>
</template>

<script>
	//Socket心跳
	let heartCheck = {
		timeout: 5000,
		timeoutObj: null,
		serverTimeoutObj: null,
		reset: function () {
			clearTimeout(this.timeoutObj);
			clearTimeout(this.serverTimeoutObj);
			return this;
		},
		start: function () {
			this.timeoutObj = setInterval(()=> {
				console.log("发送ping");
				uni.sendSocketMessage({
					data:"ping",
				});
				// this.serverTimeoutObj = setTimeout(() =>{
				// 	console.log("aaa")
				// 	uni.closeSocket();
				// }, this.timeout);
			}, this.timeout);
		}
	};

	export default {
		data(){
			return{
				meeting_title: '',
				content: {},
				link_info: {},
				client_id: '',
				joinList: {here:[],remote:[]},
				lockReconnect: false,
				timer: null,
				limit: 1,
				talk: '',
				talkList: [],
				scrollTop: 0,
				key: '',
				waiting:false,
				bigcode: false,
				qr_info: "",
                recorderManager : uni.getRecorderManager(),
                audio_id: '',
                innerAudioContext: "",
				is_speaking:false,
				speaking_time:0,
				speaking_status:"录音中...",
				speakingTimeoutObj:"",
				speaking_client_id:"",
				is_display:[],
				isPlay:false
			}
		},
		updated(){
			var This = this;
			uni.createSelectorQuery().select('.talk-box').boundingClientRect(function(rect) {
				if(rect != null)
					This.scrollTop = rect.height+'px';
			}).exec()
		},
		onShow(){
			this.key = uni.getStorageSync('key');
			this.getNowMeetingContent();
			// uni.onSocketClose();
			this.linkSocket();
			this.getOnlineUserList();
			let This = this;
			wx.onNetworkStatusChange(function (res) {
				console.log(res.isConnected)
				console.log(res.networkType)
				uni.closeSocket();
				This.linkSocket();
				This.getNowMeetingContent();
				This.getOnlineUserList();
			})
		},
		onHide(){
			uni.closeSocket();
			// Object.assign(this.$data, this.$options.data());
			// this.client_id = '';
		},
		onUnload(){
			uni.closeSocket();
			// this.client_id = '';
		},
		methods:{
			//播放音频
			playAudio(index) {
				if(!this.isPlay){
					this.innerAudioContext = uni.createInnerAudioContext();
					this.innerAudioContext.autoplay = true;
					this.innerAudioContext.src = this.talkList[index].chat_audio_url;
					this.innerAudioContext.play();
					this.isPlay = true;
					uni.showLoading({
						title: '播放中...'
					});
					this.innerAudioContext.onPlay(() => {
						console.log(this.innerAudioContext.src, "src")

					});
					this.innerAudioContext.onEnded(() => {
						console.log("播放结束")
						uni.hideLoading()
						this.isPlay = false;
						this.innerAudioContext.destroy();
						this.innerAudioContext = ""
					});
				}else{
					if(this.innerAudioContext != ""){
						this.innerAudioContext.stop();
						this.innerAudioContext.onStop(() => {
							uni.hideLoading()
							this.isPlay = false;
							this.innerAudioContext.destroy();
						})
					}
				}
			},
		    //结束录音
            stopAudio(){
                uni.hideToast();
                var _this = this;
                this.recorderManager.onStop((res) => {
                    console.log('recorder stop', res)
                    if (res.duration < 1000){
                        uni.showToast({
                            title: "录音时间太短",
                            icon: "none",
                            duration: 1000
                        });
                    }else {
                        uni.uploadFile({
                            url: 'https://zddxapi.rzkeji.com/api/file/upload-audio', // 仅为示例，非真实的接口地址
                            filePath: res.tempFilePath,
                            name: 'audio',
                            header: {
                                'content-type': 'application/json' // 默认值
                            },
                            success(res) {
                                const data = JSON.parse(res.data)
                                console.log(data)
                                if (data.level == 'success'){
                                    uni.showModal({
                                        title: '提示',
                                        content: '录音结束，是否发送录音',
                                        success (res1) {
                                            if (res1.confirm) {
                                                _this.audio_id = data.data.id;
                                                _this.UserSendMessage('audio');
                                            } else if (res1.cancel) {
                                                uni.showToast({
                                                    title: "取消成功！",
                                                    icon: "none",
                                                    duration: 1000
                                                });
                                            }
                                        }
                                    })
                                }
                                // _this.imgList.push(data.data.img_url)
                                // _this.imgIdList.push(data.data.id)
                            }
                        })
                    }
                })
                this.recorderManager.stop();
            },
			//录音
			getAudio(){
				if(this.speaking_client_id != ""){
					uni.showToast({
						title: "广播发言中,暂停其他发言！",
						icon: 'none',
						duration: 1000
					})

					return false;
				}

				uni.showToast({
					title: "请开始说话...",
					icon: 'loading',
					duration: 60000
				})
                this.recorderManager.onStart(() => {
                    console.log('recorder start')
                })
				const options = {
					duration: 60000,
					sampleRate: 16000,
					numberOfChannels: 1,
					encodeBitRate: 48000,
					format: 'mp3',
					frameSize: 50
				}
                this.recorderManager.start(options)
			},
			//链接socket
			linkSocket(){
				var This = this;
				uni.connectSocket({
					url: 'wss://api.rzkeji.com',
					success() {
						This.initEventHandle()
					},
					error(a){
						console.log(">>>>>",a)
					}
				});
			},
			//初始化socket事件
			initEventHandle(){
				this.limit = 1;
				var This = this;
				uni.onSocketOpen(function (res) {
					console.log('socket链接打开');
					heartCheck.reset().start();
				});
				uni.onSocketClose(function (res) {
					console.log('WebSocket断开！',);
					heartCheck.reset();
					This.client_id = '';
					// This.reconnect()
				});
				uni.onSocketError(function (res) {
					console.log('WebSocket连接错误！');
					This.reconnect()
				});
				uni.onSocketMessage(function (res) {
					console.log(res)
					console.log('>>>>返回:',res.data);
					//收到消息
					if (res.data == "ping"){
						// heartCheck.reset().start();
						// This.getOnlineUserList();
					}else{
						let data = JSON.parse(res.data);
						console.log('>>>>data:',res.data);
						if(data.handle == 'init'){
							This.client_id = false;
							if(!This.client_id){
								This.client_id = data.client_id;
								This.userJoinMeeting();//用户参加会议
							}
						}
						if(data.handle == 'user_online'){
							if (data.data.join_mode == 0){
								let is_true = This.clearch(This.joinList.here,data.client_id);
								if (is_true){
									This.joinList.here.push(data.data)
								}
							}else {
								let is_true = This.clearch(This.joinList.remote,data.client_id);
								if (is_true){
									This.joinList.remote.push(data.data)
								}
							}
							//用户参加会议，后端数据返回

						}
						if(data.handle == 'logout'){
							This.joinList.here.forEach((item,index)=>{
								if(item.client_id == data.client_id){
									This.joinList.here.splice(index,1);
								}
							})
							This.joinList.remote.forEach((item,index)=>{
								if(item.client_id == data.client_id){
									This.joinList.remote.splice(index,1);
								}
							})
							if(This.speaking_client_id != "" && This.speaking_client_id == data.client_id){
								This.speaking_client_id = "";
								uni.closeSocket();
							}
							if(This.client_id != "" && This.client_id == data.client_id){
								uni.closeSocket();
							}
						}
						if(data.handle == "start_speaking"){
							This.speaking_client_id = data.speak_client_id
						}
						if(data.handle == "end_speaking"){
							This.speaking_client_id = ""
						}
						//切换PPT
						if(data.handle == 'ppt_info'){
							This.waiting = false;
							This.content = data.data.content_info;
							This.link_info = data.data.link_info;
							This.meeting_title = data.data.meeting_title;
						}
						//聊天信息
						if(data.handle == 'chat_info'){
							This.talkList.push(data.data);
							This.is_display.push(0)
						}
					}
				});
			},
			async clearch(data,id){
				let ret = false;
				await data.forEach((item,index)=>{
					if(item.client_id == id){
						ret = true;
					}
				})
				return ret;
			},
			//断开重连
			reconnect(){
				if (this.lockReconnect) return;
				this.lockReconnect = true;
				clearTimeout(this.timer)
				if (this.limit<12){
					this.timer = setTimeout(() => {
						this.linkSocket();
						this.lockReconnect = false;
					}, 2000);
					this.limit = this.limit+1;
				}
			},
			//发送聊天信息
			async UserSendMessage(type){
            	if(type == "text"){
					if(this.speaking_client_id != ""){
						uni.showToast({
							title: "广播发言中,暂停其他发言！",
							icon: 'none',
							duration: 1000
						})

						return false;
					}
				}
				let params = {
					content: this.talk,
					key:this.key,
					client_id:this.client_id,
					user_token: uni.getStorageSync('userToken'),
                    content_type: type,
                    audio_id : this.audio_id
				}
				let res = await this.$api.UserSendMessage(params);
				if(res.data.level == "success"){
					this.talk = '';
                    this.audio_id = '';
				}else{
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 1000
					})
				}
			},
			//向服务器发送信息
			sendSocketMessage(data=''){
				uni.sendSocketMessage({
					data: data
				});
			},
			//用户参与会议
			async userJoinMeeting(key=''){
				let params = {
					user_token: uni.getStorageSync('userToken'),
					key:this.key,
					client_id:this.client_id,
					mode : uni.getStorageSync('mode')
				}
				let res = await this.$api.userJoinMeeting(params);
				if(res.data.level == "success"){
					uni.showToast({
						title: '已加入会议',
						icon: 'none',
						duration: 1000
					})
					this.getOnlineUserList();
				}else{
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 1000
					})
				}
			},
			//获取当前会议内容
			async getNowMeetingContent(key='',link_id='',content_id=''){
				let params = {
					key:this.key,
				}
				let res = await this.$api.getNowMeetingContent(params);
				if(res.data.level == "success"){
					if(res.data.data.has_start_meeting == 1){
						this.waiting = false;
					}else {
						this.waiting = true;
					}
					this.content = res.data.data.content_info;
					this.link_info = res.data.data.link_info;
					this.meeting_title = res.data.data.meeting_title;
					this.qr_info = res.data.data.qr_info;
				}else{
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 1000
					})
				}
			},
			//获取在线人数
			async getOnlineUserList(key='',link_id='',content_id=''){
				let params = {
					key:this.key,
				}
				let res = await this.$api.getOnlineUserList(params);
				console.log(res.data)
				if(res.data.level == "success"){
					this.joinList = res.data.data;
				}else{
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 1000
					})
				}
			},
			//退出会议
			outWaiting(){
				// uni.closeSocket();
				uni.setStorageSync('key','')
				uni.reLaunch({
					url:"/pages/home/home"
				})
			},
			//打开二维码
			openQRcode(){
				if (this.bigcode){
					this.bigcode = false;
				} else {
					this.bigcode = true;
				}

			},

			async startSpeak(){
            	if(this.is_speaking == true){
					this.is_speaking = false
            		return false;
				}
				uni.showLoading({
					title: '正在发起...',
					mask:true
				});
				let params = {
					key:this.key,
					status:"start",
					client_id:this.client_id,
					user_token: uni.getStorageSync('userToken'),
				}
				let res = await this.$api.setAllSpeakStatus(params);
				if(res.data.level == "success"){
					uni.hideLoading();
					this.is_speaking = true;
					this.getSpeakingAudio()
				}else {
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 1000
					})
				}
			},
			getSpeakingAudio(){
				this.recorderManager.onStart(() => {
					console.log("start")
				})

				const options = {
					duration: 60000,
					sampleRate: 16000,
					numberOfChannels: 1,
					encodeBitRate: 48000,
					format: 'mp3',
					frameSize: 50
				}
				this.recorderManager.start(options)
				this.speakingTimeoutObj = setInterval(() => {
					if(this.speaking_time < 60){
						this.speaking_status="录音中..."
						this.speaking_time = this.speaking_time + 1;
					}else {
						this.speaking_status="发送中..."
						this.speaking_time = 0
						clearInterval(this.speakingTimeoutObj)
						this.stopSpeaking()
					}
				}, 1000);
			},
			stopSpeaking(){
				var _this = this;
				_this.speaking_time = 0
				clearInterval(this.speakingTimeoutObj)
				this.recorderManager.onStop((res) => {
					console.log('recorder stop', res)
					if (res.duration < 1000){
						uni.showToast({
							title: "录音时间太短",
							icon: "none",
							duration: 1000
						});
					}else {
						uni.uploadFile({
							url: 'https://zddxapi.rzkeji.com/api/file/upload-audio', // 仅为示例，非真实的接口地址
							filePath: res.tempFilePath,
							name: 'audio',
							header: {
								'content-type': 'application/json' // 默认值
							},
							success(res) {
								const data = JSON.parse(res.data)
								console.log(data)
								if (data.level == 'success'){
									uni.showModal({
										title: '提示',
										content: '完成一段发言，是否发送',
										success (res1) {
											if (res1.confirm) {
												_this.audio_id = data.data.id;
												_this.UserSendMessage('audio');
												if(_this.is_speaking){
													_this.getSpeakingAudio()
												}
											} else if (res1.cancel) {
												uni.showToast({
													title: "取消成功！",
													icon: "none",
													duration: 1000
												});
												if(_this.is_speaking){
													_this.getSpeakingAudio()
												}
											}
										}
									})
								}
								// _this.imgList.push(data.data.img_url)
								// _this.imgIdList.push(data.data.id)
							}
						})
					}
				})
				this.recorderManager.stop();
			},
			async closeSpeaking(){
				let params = {
					key:this.key,
					status:"stop",
					client_id:this.client_id,
					user_token: uni.getStorageSync('userToken'),
				}
				let res = await this.$api.setAllSpeakStatus(params);
				if(res.data.level == "success"){
					clearInterval(this.speakingTimeoutObj)
					this.speaking_time = 0
					this.stopSpeaking();
					this.is_speaking = false
				}else {
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 1000
					})
				}
			}
		}
	}
</script>
<style lang='scss' scoped>
	.attendee{
		width: 100vw;
		min-height: 100vh;
		background-color: #d90913;
		/*background: url("http://file.rzkeji.com/web/dang/wxapp/back.png") no-repeat;*/
		/*background-size: 100%;*/
		.maxqrcode{
			position: fixed;
			z-index: 20000;
			top: 0;
			left: 0;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;
			width: 100vw;
			height: 100vh;
			background-color: rgba(0,0,0,0.8);
			img{
				width: 100%;
				padding: 20rpx;
				background-color: #ffffff;
			}
		}
		.qrcodenav{
			position: fixed;
			z-index: 9999;
			right: 20rpx;
			bottom: 20%;
			width: 50rpx;
			height: 50rpx;
			img{
				width: 100%;
				height: 100%;
			}
		}
		.waiting_out{
			width: 100%;
			padding: 10px;
			.send{
				width: 100%;
				height: 80rpx;
				line-height: 80rpx;
				text-align: center;
				color: #FFFFFF;
				background-color: #ffda2f;
				border-radius: 12rpx;
				margin-top: 50rpx;
			}
		}
		.waiting_content{
			/*display: flex;*/
			/*align-items: center;*/
			/*justify-content: center;*/
			/*flex-direction: column;*/
			width: 100vw;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			text-align: center;
			color: #ffda2f;
		}
		.title{
			width: 100%;
			height: 200rpx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			color: #ffda2f;
			.meeting-theme{
				font-size: 38rpx;
				margin-bottom: 30rpx;
				text-align: center;
			}
			.section{
				font-size: 28rpx;
				text-align: center;
			}
		}
		.ppt{
			width: 750rpx;
			.ppt-img{
				width: 100%;
			}
		}
		.ppt-text{
			border: 1px solid #ffda2f;
			border-radius: 14rpx;
			padding: 20rpx;
			color: #ffda2f;
			font-size: 28rpx;
			line-height: 42rpx;
		}
		.talk{
			margin-top: 20rpx;
			width: 100%;
			padding:0 20rpx;
			.talk-warp{
				width: 674rpx;
				border: 1px solid #ffda2f;
				border-radius: 14rpx;
				padding: 20rpx;
				height: 300rpx;
				overflow: scroll;
				.talk-box{
					width: 100%;
					.talk-list{
						display: flex;
						align-items: center;
						margin-bottom: 14rpx;
						.talk-list-info{
							color: #ffda2f;
							display: flex;
							flex-direction: column;
							justify-content: center;
							align-items: center;
							img{
								width: 60rpx;
								height: 60rpx;
								border-radius: 50%;
								margin-right: 8rpx;
							}
							span{
								margin-top: 4rpx;
								font-size: 22rpx;
							}
						}
						.talk-list-content{
							font-size: 24rpx;
							color: #ffda2f;
							margin-left: 8rpx;

							.icon-audio{
								animation: heartAnimation 0.7s linear 0s infinite;
							}
							@keyframes heartAnimation {
								form {
									transform: scale(0.9,0.9);
								}
								to {
									transform: scale(1.1,1.1);
								}
							}
						}
					}
				}
			}
			.talk-input{
				padding: 20rpx 0;
				width: 100%;
				display: flex;
				align-items: center;
				img{
					width: 60rpx;
					height: 60rpx;
				}
				input{
					width: 580rpx;
					border-bottom: 1px solid #ffda2f;
					color: #ffda2f;
				}
				span{
					color: #FFFFFF;
					font-size: 32rpx;
					width: 140rpx;
					text-align: center;
					height: 60rpx;
					line-height: 60rpx;
					border-radius: 50rpx;
					background-color: #ffda2f;
					margin-left: 4rpx;
				}
			}
		}
		.attendee-count{
			width: 100%;
			border: 1px solid #ffda2f;
			border-radius: 14rpx;
			padding: 10rpx;
			margin-bottom: 20rpx;
			background-color:#d90913;
			.attendee-count-title{
				font-size: 36rpx;
				color: #ffda2f;
				margin-bottom: 20rpx;
			}
			.attendee-count-content{
				height: 142rpx;
				display: flex;
				flex-wrap: wrap;
				overflow-x: hidden;
				overflow-y: scroll;
				.attendee-count-list{
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;
					margin: 0 14rpx 20rpx 0;
					img{
						width: 80rpx;
						height: 80rpx;
						border-radius: 50%;
					}
					span{
						height: 42rpx;
						line-height: 42rpx;
						font-size: 28rpx;
						color: #ffda2f;
					}
				}
			}
		}

		.speak{
			position: fixed;
			z-index: 900;
			display: block;

			.bk{
				position: fixed;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background: #000000;
				opacity: 0.8;
				filter: alpha(opacity = 0);
				z-index: 901;
			}

			.content{
				width: 80%;
				background: #fff;
				position: fixed;
				margin: 0px auto 0 -40%;
				left: 50%;
				border-color: #fff;
				border-width: 5px 0px;
				z-index: 1001;
				top: 45%;
				text-align: center;
				height: auto;
				border-radius: 6px;

				p{
					padding: 30rpx 10rpx 10rpx 10rpx;
					font-size: 30rpx;
				}
				button{
					background-color: #dd524d;
					width: 50%;
					margin: 20rpx auto;
					font-size: 28rpx;
					color: white;
				}
			}
		}
	}
</style>